﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;


public class HTTPServer
{
    private string address;
    public int port = 5555;

    private HttpListener listener;
    private bool shutdown;
    public event Action<List<PostValue>> onPostEvent;
    public void Start(string ip, int port, string suffix)
    {
        shutdown = false;
        address = string.Format("http://{0}:{1}/{2}/", ip, port, suffix);
        StartServer();
    }
    public void Close()
    {
        shutdown = true;
        listener.Close();
    }
    public void StartServer()
    {
        try
        {
            listener = new HttpListener();
            listener.Prefixes.Add(address);

            listener.Start();
            LogInfo("启动服务器成功:" + address);
            listener.BeginGetContext(ListenCB, null);
        }
        catch (Exception ex)
        {
            LogError("启动服务器失败：" + ex);
        }
    }

    private void ListenCB(IAsyncResult ar)
    {
        try
        {
            if (shutdown)
                return;

            HttpListenerContext ctx = listener.EndGetContext(ar);
            ctx.Response.StatusCode = 200;
            if (ctx.Request.HttpMethod == "GET")
                Task.Run(() => { GetHandle(ctx); });
            else if (ctx.Request.HttpMethod == "POST")
                Task.Run(() => { PostHandle(ctx); });
            listener.BeginGetContext(ListenCB, null);
        }
        catch (Exception ex)
        {
            LogError(ex);
        }

    }

    //GET请求
    private void GetHandle(HttpListenerContext ctx)
    {
        string body = Path.GetFileName(ctx.Request.RawUrl);
        if (body == "favicon.ico")
            return;

        //if (onGetEvent != null)
        //    onGetEvent(body);
        //获取RawUrl
        //string rawUrl = Path.GetFileName(ctx.Request.RawUrl);
        //接收Get参数
        //string username = ctx.Request.QueryString["username"];


        //使用Writer输出http响应代码,UTF8格式
        using (StreamWriter sw = new StreamWriter(ctx.Response.OutputStream, Encoding.UTF8))
        {
            sw.WriteLine(string.Format("GET Request  Time is:{0}", System.DateTime.Now));
            sw.Flush();
            sw.Close();
            sw.Dispose();
        }
    }

    private void PostHandle(HttpListenerContext ctx)
    {
        //List<PostValue> form = DecodePost.GetHttpListenerPostValue2(ctx);
        //if (onPostEvent != null)
        //    onPostEvent(form);

        //DecodePost.GetHttpListenerPostValue2(ctx);

        using (StreamWriter sw = new StreamWriter(ctx.Response.OutputStream, Encoding.UTF8))
        {
            sw.WriteLine(string.Format("GET Request  Time is:{0}", System.DateTime.Now));
            sw.Flush();
            sw.Close();
            sw.Dispose();
        }
    }

    public static void LogInfo(object obj)
    {
        Console.WriteLine(obj);
    }
    public static void LogError(object obj)
    {
        Console.WriteLine(obj);
    }
}

